package main

import (
	"fmt"
	"github.com/streadway/amqp"
	"time"
)

func main() {
	dial, err := amqp.Dial("amqp://guest:guest@127.0.0.1:5673/")
	if err != nil {
		panic(err)
	}

	channel, err := dial.Channel() // 创建一个连接
	if err != nil {
		panic(err)
	}

	q, err := channel.QueueDeclare( // 根据连接创建一个队列
		"go_q1",
		true,
		false,
		false,
		false,
		nil)

	if err != nil {
		panic(err)
	}

	go consume("c1", dial, q.Name) // 开启一个接受队列的连接
	go consume("c2", dial, q.Name)

	i := 0
	for { // 循环给队列发消息
		i++
		err := channel.Publish(
			"",
			q.Name,
			false,
			false,
			amqp.Publishing{
				Body: []byte(fmt.Sprintf("msg %d", i)),
			},
		)

		if err != nil {
			fmt.Println(err.Error())
		}
		time.Sleep(200 * time.Millisecond)
	}
}

func consume(consumer string, conn *amqp.Connection, q string) {
	ch, err := conn.Channel() // 创建一个连接
	if err != nil {
		panic(err)
	}

	defer ch.Close()
	msgs, err := ch.Consume( // 从队列里取出消息
		q,
		consumer,
		true,
		false,
		false,
		false,
		nil,
	)

	if err != nil {
		panic(err)
	}

	for msg := range msgs {
		fmt.Printf("%s: %s\n", consumer, msg.Body)
	}
}
